package jp.co.sega.sonic_jump.monthly.sum;

import java.io.*;
import java.net.*;
import java.util.*;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.os.Build;

public class IniParser {

    public static boolean isConnectedToWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) return false;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // Para Android 6.0 (API 23) ou superior
            Network network = cm.getActiveNetwork();
            if (network == null) return false;

            NetworkCapabilities capabilities = cm.getNetworkCapabilities(network);
            return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
        } else {
            // Para versões mais antigas
            return cm.getActiveNetworkInfo() != null &&
                   cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI &&
                   cm.getActiveNetworkInfo().isConnected();
        }
    }

    public static List<Event> parseFromUrl(String fileUrl) throws IOException {
        if (!isConnectedToWifi(Shell.sInstance)) {
            return null;
        }
        
        List<Event> events = new ArrayList<>();

        // Abre conexão HTTP
        URL url = new URL(fileUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            System.err.println("Connection error: " + responseCode);
            events = null;
            return events; // Retorna null em caso de erro
        }
        
        // Lê o conteúdo do arquivo
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        
        String line;
        int eventNumber = 0;
        String name = "", textures = "", character = "";
        String unlockable = "";
        int rings = 0, level = 0, act = 0, bluehoops = 0;

        boolean insideEvent = false;

        while ((line = reader.readLine()) != null) {
            line = line.trim();

            if (line.startsWith("//")) continue;

            if (line.startsWith("Event")) {
                insideEvent = true;
                String[] parts = line.split(" ");
                eventNumber = (parts.length > 1) ? Integer.parseInt(parts[1]) : 0;
                name = textures = character = unlockable = "";
                rings = level = act = bluehoops = 0;
                continue;
            }

            if (line.equals("{")) continue;

            if (line.equals("}")) {
                if (insideEvent) {
                    events.add(new Event(eventNumber, name, textures, level, act, rings, bluehoops, character, unlockable));
                    insideEvent = false;
                }
                continue;
            }

            if (line.contains(":")) {
                String[] parts = line.split(":", 2);
                String key = parts[0].trim();
                String value = parts[1].trim();

                switch (key) {
                    case "name": name = value; break;
                    case "textures": textures = value; break;
                    case "level": level = Integer.parseInt(value); break;
                    case "act": act = Integer.parseInt(value); break;
                    case "rings": rings = Integer.parseInt(value); break;
                    case "bluehoops": bluehoops = Integer.parseInt(value); break;
                    case "character": character = value; break;
                    case "unlockable": unlockable = value; break;
                }
            }
        }

        reader.close();
        return events;
    }

    public static List<Event> parseFile(String filePath) throws IOException {
        List<Event> events = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(filePath));

        String line;
        int eventNumber = 0;
        String name = "", textures = "", mission = "", character = "";
        String unlockable = "", day = "", duration = "";
        int rings = 0, bluehoops = 0, level = 0, act = 0;

        boolean insideEvent = false;

        while ((line = reader.readLine()) != null) {
            line = line.trim();

            // Ignora comentários
            if (line.startsWith("//")) continue;

            // Quando encontra um evento novo, reseta os valores e extrai o número
            if (line.startsWith("Event")) {
                insideEvent = true;

                // Extrai o número do evento
                String[] parts = line.split(" ");
                if (parts.length > 1) {
                    try {
                        eventNumber = Integer.parseInt(parts[1]);
                    } catch (NumberFormatException e) {
                        eventNumber = 0; // Se não puder converter, define como 0
                    }
                } else {
                    eventNumber = 0;
                }

                // Reseta valores do evento atual
                name = textures = character = unlockable = "";
                rings = bluehoops = level = act = 0;
                continue;
            }

            // Se for abertura de bloco "{", apenas continua
            if (line.equals("{")) continue;

            // Se for fechamento "}", adiciona o evento na lista
            if (line.equals("}")) {
                if (insideEvent) {
                    events.add(new Event(eventNumber, name, textures, level, act, rings, bluehoops, character, unlockable));
                    insideEvent = false;
                }
                continue;
            }

            // Divide pelo `:` para pegar chave e valor
            if (line.contains(":")) {
                String[] parts = line.split(":", 2);
                String key = parts[0].trim();
                String value = parts[1].trim();

                // Associa os valores às variáveis corretas
                switch (key) {
                    case "name": name = value; break;
                    case "textures": textures = value; break;
                    case "level": level = Integer.parseInt(value); break;
                    case "act": act = Integer.parseInt(value); break;
                    case "rings": 
                        try {
                            rings = Integer.parseInt(value);
                        } catch (NumberFormatException e) {
                            rings = 0;
                        }
                        break;
                    case "bluehoops": 
                        try {
                            bluehoops = Integer.parseInt(value);
                        } catch (NumberFormatException e) {
                            bluehoops = 0;
                        }
                        break;
                    case "character": character = value; break;
                    case "unlockable": unlockable = value; break;
                }
            }
        }

        reader.close();
        return events;
    }
}